package com.vonchenchen.simple_downloader.downloader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URL;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;

/**
 * Created by lidechen on 9/15/16.
 */
public class ThreadInfo {

    public static ExecutorService POOL_Thread;

    public static LinkedList<ThreadInfo> mIdleDownLoadThreadList;
    public static LinkedList<ThreadInfo> mBusyDownLoadThreadList;

    public int threadId;

    public long startPos;
    public long endPos;
    public long currPos;
    public URL url;

    public File targetFile;

    public boolean isStart = false;
    public boolean isComplite;

    public DownLoadThread downLoadThread;

    public String toJsonString(){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("threadId", threadId);
            jsonObject.put("startPos", startPos);
            jsonObject.put("endPos", endPos);
            jsonObject.put("currPos", currPos);
            jsonObject.put("url", url.toString());
            jsonObject.put("targetFile", targetFile.getAbsolutePath());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    public synchronized void startThread(){
        mIdleDownLoadThreadList.remove(ThreadInfo.this);
        mBusyDownLoadThreadList.add(ThreadInfo.this);

        downLoadThread.setThread(ThreadInfo.this);
        isStart = true;
        //downLoadThread.start();
        POOL_Thread.execute(downLoadThread);
    }

    public synchronized void stopThread(){
        mBusyDownLoadThreadList.remove(ThreadInfo.this);
        mIdleDownLoadThreadList.add(ThreadInfo.this);
        downLoadThread.resetThread();
    }
}
